
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:iidx_progress_tool/components/detail/tag_edit_dialog.dart';
import 'package:iidx_progress_tool/data/model/difficulty_progress.dart';
import 'package:iidx_progress_tool/data/model/music_data.dart';
import 'package:iidx_progress_tool/data/model/music_progress.dart';
import 'package:iidx_progress_tool/data/services/user_progress_service.dart';

class _DifficultyItem {
  bool isExpand;
  String title;
  int level;
  DifficultyProgress? progress;

  _DifficultyItem({
    required this.isExpand,
    required this.title,
    required this.level,
    this.progress
  });
}

class DifficultyExpansionPanelList extends StatefulWidget {
  final MusicData musicData;

  const DifficultyExpansionPanelList({super.key,
    required this.musicData});

  @override
  State<StatefulWidget> createState() {
    return _DifficultyExpansionPanelListState();
  }
}

class _DifficultyExpansionPanelListState extends State<DifficultyExpansionPanelList> {
  List<_DifficultyItem> _items = [];
  MusicProgress? _progress;
  MusicProgressService _service = MusicProgressService();

  @override
  void initState() {
    super.initState();
    _loadProgressData().then((progress) {
      _progress = progress;
      setState(() {
        _items = _generateItem(progress, widget.musicData);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: Container(
          child: ExpansionPanelList(
              expansionCallback: (int index, bool isExpanded) {
                setState(() {
                  _items[index].isExpand = isExpanded;
                });
              },
              children: _items.map<ExpansionPanel>((_DifficultyItem item) {
                return ExpansionPanel(
                    headerBuilder: (BuildContext context, bool isExpanded) {
                      return ListTile(
                        title: Text("${item.title} ${item.level}"),
                      );
                    },
                    body: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 15),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 5),
                            child: Text(
                              "Clear Status",
                              style: const TextStyle(fontSize: 15),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 5),
                            child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Expanded(
                                    child: SingleChildScrollView(
                                      scrollDirection: Axis.horizontal,
                                      child: Wrap(
                                        spacing: 5,
                                        runSpacing: 5,
                                        children: _progressList(item.progress),
                                      ),
                                    ),
                                  ),
                                ]
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 5),
                            child: Text(
                              "Tags",
                              style: const TextStyle(fontSize: 15),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 5),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Expanded(
                                  child: SingleChildScrollView(
                                    scrollDirection: Axis.horizontal,
                                    child: Wrap(
                                      spacing: 5,
                                      runSpacing: 5,
                                      children: _tagList(item.progress)
                                    ),
                                  ),
                                ),
                                FilledButton.tonal(
                                    onPressed: () {_showEditTagPressed(context, item.progress);},
                                    child: const Icon(Icons.add)
                                )
                              ],
                            )
                          ),
                        ],
                      ),
                    ),
                    isExpanded: item.isExpand
                );
              }).toList()
          ),
        )
    );
  }

  List<_DifficultyItem> _generateItem(MusicProgress progress, MusicData musicData) {
    List<_DifficultyItem> itemList = [];
    if (widget.musicData.spbLevel > 0) {
      itemList.add(
          _DifficultyItem(isExpand: false,
              title: "SP Beginner",
              level: musicData.spbLevel,
              progress: progress?.spbProgress)
      );
    }
    if (widget.musicData.spnLevel > 0) {
      itemList.add(
        _DifficultyItem(isExpand: false,
            title: "SP Normal",
            level: musicData.spnLevel,
            progress: progress?.spnProgress)
      );
    }
    if (widget.musicData.sphLevel > 0) {
      itemList.add(
        _DifficultyItem(isExpand: false,
            title: "SP Hyper",
            level: musicData.sphLevel,
            progress: progress?.sphProgress)
      );
    }
    if (widget.musicData.spaLevel > 0) {
      itemList.add(
        _DifficultyItem(isExpand: false,
            title: "SP Another",
            level: musicData.spaLevel,
            progress: progress?.spaProgress)
      );
    }
    if (widget.musicData.splLevel > 0) {
      itemList.add(
        _DifficultyItem(isExpand: false,
            title: "SP Leggendaria",
            level: musicData.splLevel,
            progress: progress?.splProgress)
      );
    }
    if (widget.musicData.dpbLevel > 0) {
      itemList.add(
        _DifficultyItem(isExpand: false,
            title: "DP Beginner",
            level: musicData.dpbLevel,
            progress: progress?.dpbProgress)
      );
    }
    if (widget.musicData.dpnLevel > 0) {
      itemList.add(
        _DifficultyItem(isExpand: false,
            title: "DP Normal",
            level: musicData.dpnLevel,
            progress: progress?.dpnProgress)
      );
    }
    if (widget.musicData.dphLevel > 0) {
      itemList.add(
        _DifficultyItem(isExpand: false,
            title: "DP Hyper",
            level: musicData.dphLevel,
            progress: progress?.dphProgress)
      );
    }
    if (widget.musicData.dpaLevel > 0) {
      itemList.add(
        _DifficultyItem(isExpand: false,
            title: "DP Another",
            level: musicData.dpaLevel,
            progress: progress?.dpaProgress)
      );
    }
    if (widget.musicData.dplLevel > 0) {
      itemList.add(
        _DifficultyItem(isExpand: false,
            title: "DP Leggendaria",
            level: musicData.dplLevel,
            progress: progress?.dplProgress)
      );
    }

    return itemList;
  }

  List<Widget> _progressList(DifficultyProgress? progress) {
    if (progress == null) {
      return [];
    }

    return [
      ChoiceChip(
        label: const Text("Normal Clear"),
        selected: progress.normalClear,
        onSelected: (bool selected) {
          setState(() {
            _updateProgressData();
            progress.normalClear = selected;
          });
        },
      ),
      ChoiceChip(
        label: const Text("Hard Clear"),
        selected: progress.hardClear,
        onSelected: (bool selected) {
          setState(() {
            _updateProgressData();
            progress.hardClear = selected;
          });
        },
      ),
      ChoiceChip(
        label: const Text("ExHard Clear"),
        selected: progress.exhardClear,
        onSelected: (bool selected) {
          setState(() {
            _updateProgressData();
            progress.exhardClear = selected;
          });
        },
      )
    ];
  }

  List<Widget> _tagList(DifficultyProgress? progress) {
    if (progress == null) {
      return [];
    }

    return progress.tags.map((tag) {
      return Chip (
        label: Text(tag.name),
      );
    }).toList();
  }

  void _showEditTagPressed(BuildContext context, DifficultyProgress? progress) {
    if (progress == null) {
      return;
    }

     showDialog(context: context, builder: (context) {
       return TagEditDialog(progress: progress, onSave: () {_updateProgressData();});
     });
  }

  Future _loadProgressData() async {
    return _service.get(widget.musicData.songId.toString());
  }

  Future _updateProgressData() async {
    return _service.save(_progress).then((_) {
      setState(() {});
    });
  }
}